package cn.jsc.basic.util;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * 手机发送验证码的工具类
 */
public class SmsUtil {

    //用户名
    private final static String UID = "taylors";
    //秘钥
    private final static String KEY = "d41d8cd98f00b204e980";

    /**
     * 发送手机验证码
     * @param phone
     * @param content
     * @return
     */
    public static String send(String phone,String content){
        PostMethod post =null;
        try {
            HttpClient client = new HttpClient();
            post = new PostMethod("http://utf8.api.smschinese.cn");
            post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码
            NameValuePair[] data ={
                    new NameValuePair("Uid", UID),new NameValuePair("Key", KEY),
                    new NameValuePair("smsMob",phone),new NameValuePair("smsText",content)};
            post.setRequestBody(data);

            client.executeMethod(post);
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode);

            String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
            return result; //打印返回消息状态

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null) {
                post.releaseConnection();
            }
        }
        return null;
    }


    public static void main(String[] args) {
        SmsUtil.send("17683809913","你的验证码是8848，请在三分钟内使用");
    }
}
